package cn.lg.soar.core.manager;

import cn.lg.soar.common.util.hardware.SystemUtils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;

/**
 * @author luguoxiang
 * @date 2022/4/7
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class LocalTokenStateManager implements ITokenStateManager{

    protected static final Logger LOGGER = LoggerFactory.getLogger(LocalTokenStateManager.class);

    protected final Cache<String, Long> cache;

    public LocalTokenStateManager() {
        this(Duration.ofMinutes(1));
    }

    public LocalTokenStateManager(Duration expire) {
        this(SystemUtils.TOTAL >>> 16, expire);
    }

    public LocalTokenStateManager(long cacheSize, Duration expire) {
        this.cache = Caffeine.newBuilder()
                .maximumSize(cacheSize)
                .initialCapacity(128)
                .expireAfterWrite(expire)
                .build();
        LOGGER.info("token cache max size {}", cacheSize);
    }

    public LocalTokenStateManager(Cache<String, Long> cache) {
        this.cache = cache;
    }


    /**
     * 保存状态
     * @param id tokenId
     * @param value tokenValue
     * @param expire 有效期
     */
    @Override
    public void put(String id, Long value, long expire) {
        cache.put(id, value);
    }

    /**
     * 根据tokenId获取tokenValue
     * @param id tokenId
     * @return
     */
    @Override
    public Long get(String id) {
        return cache.getIfPresent(id);
    }

    /**
     * 删除 tokenValue
     * @param id
     */
    @Override
    public void remove(String id) {
        cache.invalidate(id);
    }
}
